<?php
namespace Api\Controller;

use Common\Controller\ApiController;

class PayController extends ApiController {
    public $uid;
    public $my_points;
    public $timestamp;

    public function _initialize() {
        parent::_initialize();
        $this->uid = C('visitor.uid');
        $this->my_points = D('MembersPoints')->get_user_points($this->uid);//会员积分表
        $this->timestamp = time();
        if(!IS_POST){
            $this->ajaxReturn(1, '提交方式错误！');
        }
    }


    /**
     * 增值服务支付 - 成为人才顾问支付
     */
    public function payMoney(){
        $wenda = M('questionnaire_user_list')->where(['uid' => $this->userinfo['uid']])->order('id desc')->find();
        $data  = ['pay_money'=>C("qscms_gu_wen_pay_money"), 'free_quota'=>C("qscms_gu_wen_free_quota")];
        $data['level']      = $wenda['level_id'];
        $data['pay_money']  = !empty($wenda['level_id']) && $wenda['level_id']==1 ? '0' : $data['pay_money'];
        $this->ajaxReturn(0, 'ok', $data);//金牌一级支付金额和免费名额
    }



    /**
     * 增值服务支付 - 成为人才顾问支付
     */
    public function payAdvisor() {
        $orderPayType   = 17;       //升级人才顾问
        $paymentName    = 'wxpay';  //微信支付
        $htype_cn       = $htype_cn_mianfei =D('Order')->order_type[$orderPayType];
        $user           = $this->userinfo;
        $resume         = $this->isResume();
        $wxcode         = I('post.wxcode','','trim,badword');
        $is_deductible  = I('post.is_deductible',0,'intval');
        $deductible     = I('post.deductible','','floatval');
        $amount         = I('post.amount','','floatval');
        $payMoney       = C("qscms_gu_wen_pay_money");//申请金牌Ⅰ级人才顾问支付金额
        $guwenquota     = C("qscms_gu_wen_free_quota");//顾问免费名额 限金牌Ⅰ级人才顾问使用
        $pay_type       = 'mianfei';//支付提交类型
        $userinfo       = I('post.userinfo');//微信登陆用户信息
        //if($user['utype'] <> 3) $this->ajaxReturn(1,'当前用户类型不能支付');

        //if(empty($user['advisor_level']) || $user['advisor_level'] > 2) $this->ajaxReturn(1,'顾问等级错误');

        if(!$resume){
            $this->ajaxReturn(1, '用户资料不存在');
        }

        $wd = M("QuestionnaireUserList")->where(['uid'=> $user['uid'],'status'=>1])->find();
        if(!$wd){
            $this->ajaxReturn(1, '顾问审核通过的问答不存在');
        }

        /*if ($amount <> $payMoney) {
            $this->ajaxReturn(1, '提交的金额和实际支付的金额不符合');
        }*/
        /*$service_need_points = M('PersonalServiceStick')->where(array('days' => array('eq', $days)))->getField('points');
        $service_need_cash = round($service_need_points / C('qscms_payment_rate'), 2);*/

        //查询当前是否支付过
        $userOrder  = D('order')->get_order_one(['uid'=>$this->userinfo['uid'], 'order_type'=>17, 'is_paid'=>2]);
        if($userOrder){
            $this->ajaxReturn(1, '用户已经支付过，不用重复支付');
        }

        if($wd['level']==1){
            $htype_cn_mianfei   = $htype_cn_mianfei.'——初级人才顾问';
        }

        if($wd['level']==2){
            //查询免费名额是否已经用完
            $ordercount = D('order')->where(['order_type'=>17, 'is_paid'=>2, 'payment'=>'mianfei', 'service_name'=>$htype_cn.'——金牌1级人才顾问'])->count();
            if($guwenquota > $ordercount) {
                $htype_cn_mianfei   = $htype_cn_mianfei.'——金牌1级人才顾问';
            }else{
                $pay_type   = 'xianjin';
            }
        }

        if ($pay_type <> 'mianfei') {
            if (empty($wxcode)) $this->ajaxReturn(1, '微信wxcode不能为空');
        }

        $openId     = wxOpenId($wxcode, $this->userinfo['uid']);
        if (!empty($openId['status'])) $this->ajaxReturn(1, '微信openId获取失败');
        $params             = [
            'resume_id' => $resume['id'],
            'amount'    => $amount,
            'openid'    => !empty($openId['data']) ? $openId['data'] : ''
        ];
        $params = serialize($params);
        //=====判断免费名额支付=====
        if ($pay_type == 'mianfei') {
            $oid                = "M-" . date('ymd', time()) . "-" . date('His', time());//订单号
            $description        = '购买服务：' . $htype_cn . '; 免费支付';
            $order_insert_id    = D('Order')->add_order(C('visitor'), $oid, $orderPayType, $payMoney, $payMoney, 0, $htype_cn_mianfei, 'mianfei', '免费支付', $description, $this->timestamp, 2, 0, 0, $this->timestamp, $params);
            /* 会员日志 */
            write_members_log(C('visitor'), 'order', '创建增值服务订单（订单号：' . $oid . '），支付方式：免费支付', false, array('order_id' => $order_insert_id));

            //修改用户类型+++++++++++++++++++++++++++++++++

            $guwenData   = ['gw_uid'=> $wd['uid'], 'shou_quan_time'=> time(), 'has_date'=> date('Y', time()), 'level'=>$wd['level'], 'level_name'=>$wd['level_name']];
            M("GuwenLevelLog")->add($guwenData);

            //修改用户类型
            M('members')->where(['uid'=> $this->userinfo['uid']])->save(['utype'=>3, 'advisor_level'=>$wd['level'], 'advisor_level_name'=>$wd['level_name']]);
            M('ResumeSearchFull')->where(['uid'=> $this->userinfo['uid']])->save(['utype'=>3]);
            M('ResumeSearchPrecise')->where(['uid'=> $this->userinfo['uid']])->save(['utype'=>3]);

            //申请成为顾问则退出顾问人才库
            M("GuwenUser")->where(['uid'=>$this->userinfo['uid']])->delete();

            //成为人才顾问删除相关企业资料
            M('CompanyProfile')->where(['uid'=>$this->userinfo['uid']])->delete();
            M('companyImg')->where(['uid'=>$this->userinfo['uid']])->delete();//图片
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            $this->ajaxReturn(0, '支付成功！');

        } else {
            //=====现金支付=====
            $re = call_cash_pay($htype_cn, $orderPayType, $openId['data'], $paymentName, $payMoney, $is_deductible, $deductible, $params);
            if($re['status']==1) $this->ajaxReturn(1, $re['msg']);

            $this->ajaxReturn(0, 'ok', $re['data']);
        }
    }

    public function demo(){
        $union = D('JobsTmp')->where(array('id' => array('in', '8,9')))->buildSql();
        echo $union;exit;
        //推送微信通知
        $data=[
            'thing2' => ['value'=>'张全蛋有限公司'],
            'phrase1'=> ['value'=>'审核通过'],
            'time3'=> ['value'=>date('Y-m-d H:i:s', time())],
            'time4'=> ['value'=>date('Y-m-d H:i:s', time())],
        ];

        var_dump(wxMessageSend('oObsr408s2-fWCI0imDiGkbhIhyM',17837, $data));exit;

        //查看分类
        $category = D('CategoryMajor')->get_engineering_and_children(); //工程
        $category = D('CategoryJobs')->get_all_cate();//职位
        $this->ajaxReturn(0, 'ok', D('CategoryJobs')->getJobsName('502.0'));

        //退款
        $amount = 0.01;
        $amount2 = 0.01;
        $result = refund_pay('W-210202-111112', 'W-210202-111236-4895', $amount, $amount2, 'refundPay');
        print_r($result);exit;

        /*$data   = '<xml><return_code>SUCCESS</return_code><appid><![CDATA[wx149691a5b873437b]]></appid><mch_id><![CDATA[1604946733]]></mch_id><nonce_str><![CDATA[ddf70de4be0f0cd8d89df73883354f5f]]></nonce_str><req_info><![CDATA[q4mPeUI1MEPEJj9e2zKBY0nT2G2eBQY/1/BIeJsFAkBWvhlaAVQw6gvw8THA8szbnMYQOTB2QoneBD3NpBDGSFetms26wvPOCHnrG1enOisUqwOOPOsRGlgW4Iie8mpwtyUXr+HcNR1ctIg4Zrk2BnMvcCNYiWRrnt7wiEf2LHO/Cz7AqukQWIZ7kleZxMWp65l5GgDKqlwocvWgenLCXUPZFRd86AdRxLs8EUNWT3bpa3Kx2bmnYnjP+zKWCaZFsIcFdKsCtrxK9f8FFML40V67Dl8Zk5mZ1Kj5e7ND09tKsp07to1lxj5hD2fjtgee+OUUuiKvU3XE0pwqkkmioSFhd8wDyu5MMgbPsxj1ym4GuzG+NnTX1wFWLOBNz/mv5YRsCEDB8jizQdo06AgiU3EWQY6oKloYA/DkaZeGuER3V8JGeMg9Z2g0p8f2Yr/cQk1W2wzxBrWDeQkr+e4XPHWLE5j18fC8G98JZLWcH9wAOTQ91QjWh5vuQTC7xQJgYJ6dYbMVyNbHijKhuh/ciuEZJtjdm3ftMPk1LAQ9SHbqmAFX0VBiMvf6Q4gZjLW3pxvkmz/GfMfT5kuNIT/6S1f9F7pG9p/uuonfGhyI9mG4nX07iaXi86qW9LZiNcSVeJR+X+TNdZU2Bd+RT7rbhXXadvTjbmwstf6m4Ku29ORonhfoS/wrOZ27FWQ1Po8BxZBeQTzdYJwnuWZnZjWB3D+AEerAguIo2/fF31lhz3TiACyZVk3D+OAfdCVThP94ql0VcbzenzIvxXYYEvy6EHaUWpYhsdxsF/B20U0GAoTU1kGqQKvIBw51xgLLPYQ4Q4GdLAlj/7osCW5yTfH+FmtoX51UB5RayLmtanJ5FHzPU19hTwis9fsFZMnPB+sIuplE7VsLbpzOcIKebVrndv13Wxj6hdSKwkSU1h6aFtgYk8yI8z2eQgV2gUpdzipaCiZJVV26nkYH0Z+H7c3vWgYRdMD/L2H+CUAb6hQQHRef2lSweMF4btFzdqeKnNNg55SEG1nhkNSOQg70iT/tylvKa8oQqFMo91hSc1zDsms=]]></req_info></xml>';
        libxml_disable_entity_loader(true);
        $array_data = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //print_r($array_data);
        $a=base64_decode($array_data['req_info'],true);
        $reslut = openssl_decrypt($a, 'AES-256-ECB', md5('sunkoZxp20210111sunkoZxp20210111'), OPENSSL_RAW_DATA);
        //$reslut = openssl_decrypt(base64_decode($array_data), 'aes-256-ecb', md5('sunkoZxp20210111sunkoZxp20210111'));
        print_r($reslut);*/
    }

}

?>